/*
Copyright (c) 2008, Mike Gashler

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/

#ifndef __GSPINLOCK_H__
#define __GSPINLOCK_H__

#include "app.h"
#ifdef WIN32
#	include <windows.h>
#else
#	include <pthread.h>
#	include <unistd.h>
#endif


// A spin-lock for synchronization purposes
class GSpinLock
{
protected:
#ifdef _DEBUG
	const char* m_szWhoHoldsTheLock;
#endif
	unsigned int m_dwLocked;		// maintaned on all platform as posix mutexes don't have a way to get current state.
									// when not Win32 be aware that this value is shadowing the real mutex, and cannot be
									// depended on especially in a MP enviroment.
#ifndef WIN32
	pthread_mutex_t m_mutex;
#endif

public:
	GSpinLock();
	virtual ~GSpinLock();

#ifndef NO_TEST_CODE
	static void Test();
#endif // !NO_TEST_CODE

	void Lock(const char* szWhoHoldsTheLock);
	void Unlock();
	bool IsLocked() { return m_dwLocked != 0; }	// see note above about m_dwLocked.

	static HANDLE SpawnThread(unsigned int (*pFunc)(void*), void* pData);

#ifdef WIN32
	static void yield()
	{
		MSG aMsg;
		while(PeekMessage(&aMsg, NULL, WM_NULL, WM_NULL, PM_REMOVE))
		{
			TranslateMessage(&aMsg);
			DispatchMessage(&aMsg);
		}
	}
#endif

	static inline void sleep(unsigned int nMiliseconds)
	{
#ifdef WIN32
		Yield();
		Sleep(nMiliseconds);
#else // WIN32
		nMiliseconds ? usleep(nMiliseconds*1024) : sched_yield(); // it is an error to sleep for more than 1,000,000
#endif // else WIN32
	}
};


class GSpinLockHolder
{
protected:
	GSpinLock* m_pLock;

public:
	GSpinLockHolder(GSpinLock* pLock, const char* szWhoHoldsTheLock)
	{
		m_pLock = pLock;
		pLock->Lock(szWhoHoldsTheLock);
	}

	~GSpinLockHolder()
	{
		m_pLock->Unlock();
	}
};

#endif // __GSPINLOCK_H__
